from flask import request, jsonify, session
from sqlalchemy import or_
from app.forms.book import BookForm
from app.libs.redprint import Redprint
from app.models.book import Book
from app.libs.token_auth import auth

red_book = Redprint('book')


@red_book.route('/book/search')
@auth.login_required
def get_book():
    form = BookForm(request.args.to_dict())
    form.validate_for_api()
    q = '%' + form.q.data + '%' # 模糊查询的对象必须使用%号包围起来
    books = Book.query.filter(or_(Book.title.like(q), Book.author.like(q))).all()
    new_books = [book.hide('summary', 'id') for book in books]
    return jsonify(new_books)


@red_book.route('/book/detail/<isbn>')
@auth.login_required
def book_detail(isbn):
    book = Book.query.filter_by(isbn=isbn).first_or_404()
    return jsonify(book)


@red_book.route('/<int:number>')
def index(number):
    session['number'] = number
    print(session['number'])
    print(session['number'])
    return '123'
